/*
 * @Description:
 * @Version: 1.0
 * @Autor: laikt
 * @Date: 2021-01-11 13:54:49
 * @LastEditors: laikt
 * @LastEditTime: 2021-01-12 17:06:56
 */
import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository, getConnection } from 'typeorm'
import { Table } from './entity/table.entity'

@Injectable()
export class TableService {
    // typeorm
    constructor(
        @InjectRepository(Table)
        private tableRepository: Repository<Table>
    ) {}
    async findTableColumn({ code }): Promise<Table[] | undefined> {
        return this.tableRepository.find({ code })
    }
    async create({ code, tableColumn }) {
        // 获取连接并创建新的queryRunner
        const connection = getConnection()
        const queryRunner = connection.createQueryRunner()

        // 使用我们的新queryRunner建立真正的数据库连
        await queryRunner.connect()

        // 开始事务：
        await queryRunner.startTransaction()

        try {
            // 对此事务执行一些操作：

            // await this.tableRepository.save(tableColumn.map(e=>{
            //     return {code,...e}
            // }))
            await tableColumn.forEach(async value => {
                await this.tableRepository.save({ code, ...value })
            })

            // 提交事务：
            await queryRunner.commitTransaction()
            return {
                code: 200,
                msg: '创建成功'
            }
        } catch (err) {
            // 有错误做出回滚更改
            await queryRunner.rollbackTransaction()
            return {
                code: 500,
                msg: err
            }
        }

        // try {
        //     tableColumn.forEach(async (value) => {
        //         await this.tableRepository.save({code,...value})
        //     })
        // } catch (error) {
        //     return {
        //         code: 500,
        //         msg: error
        //     }
        // }
    }
}
